package com.springBoot.springBootSysCore.modules.shiro;

import com.springBoot.springBootSysCore.common.config.Global;
import com.springBoot.springBootSysCore.common.utils.StringUtils;
import com.springBoot.springBootSysCore.modules.entity.system.SysResource;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * url权限控制
 * 用处初始化或者重置拦截器链
 * @author timo
 */
@Service
public class ShiroFilerChainManager {
	@Autowired
	private CustomDefaultFilterChainManager filterChainManager;
	private Map<String, NamedFilterList> defaultFilterChains;
	@PostConstruct
	public void init() {
		defaultFilterChains = new HashMap<String, NamedFilterList>(filterChainManager.getFilterChains());
	}
	public void initFilterChains(List<SysResource> resources ) {
		// 1、首先删除以前老的filter chain并注册默认的
		filterChainManager.getFilterChains().clear();
		if (defaultFilterChains != null) {
			filterChainManager.getFilterChains().putAll(defaultFilterChains);
		}
		// 2、循环URL Filter 注册filter chain
		for (SysResource res : resources) {
			String url = res.getUrl();
			// 注册roles filter
//			if (!StringUtils.isEmpty(urlFilter.getRoles())) {
//				filterChainManager.addToChain(url, "roles",urlFilter.getRoles());
//			}
			// 注册perms filter
			if (!StringUtils.isEmpty(res.getCode())) {
				filterChainManager.addToChain(Global.getAdminPath()+url, "perms",res.getCode());
			}
		}
	}
}
